﻿using System;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Web;
using Jink.Protocol.Core;
using Jink.Protocol.Core.Headers;
using Jink.Protocol.Core.Verbs;
using XenoGears.Collections.Dictionaries;
using XenoGears.Functional;
using XenoGears.Reflection.Simple;
using System.Linq;

namespace Jink.Protocol.Media.Http
{
    public class HttpRequestMedia : IRequestMedia
    {
        private readonly HttpRequest _request;
        private readonly HttpContext _context;

        public HttpRequestMedia(HttpRequest request)
        {
            _request = request;
            _context = (HttpContext)_request.Get("_context");
        }

        public static implicit operator HttpRequestMedia(HttpRequest request)
        {
            return new HttpRequestMedia(request);
        }

        public IPrincipal User { get { return _context.User; } }

        // todo. implement url decode
        public String AbsoluteUrl { get { throw new NotImplementedException(); } }
        public String RelativeUrl { get { throw new NotImplementedException(); } }
        public Verb Verb { get { return _request.HttpMethod.ToVerb(); } }

        public Encoding ContentEncoding { get { return _request.ContentEncoding; } }
        public String ContentType { get { return _request.ContentType; } }
        public Stream ContentStream { get { return _request.InputStream; } }

        public ReadOnlyDictionary<RequestHeader, String> Headers
        {
            get { return _request.Headers.Cast<String>().ToDictionary(key => key.ToRequestHeader(), key => _request.Headers[key]).ToReadOnly(); }
        }

        public ReadOnlyDictionary<String, String> Cookies
        {
            get { return _request.Cookies.Cast<HttpCookie>().ToDictionary(coo => coo.Name, coo => coo.Value).ToReadOnly(); }
        }

        public ReadOnlyDictionary<String, String> Form
        {
            get { return _request.Form.Cast<String>().ToDictionary(key => key, key => _request.Form[key]).ToReadOnly(); }
        }
    }
}
